Take a look at this question. We have a class bird and
then we have a subclass or child class called penguin
that inherits from bird. There's a fly method in bird, and a feathers method in bird, and a fly method in penguin. Then we create a bird object and a penguin object and
we ask each of those, the bird object to fly the
penguin object to fly, the bird object to execute
the feathers method, the penguin object to
execute the feathers method. So what's going to be
the output of that? We can look at this URL, which is Python Tutor to
see exactly what happens. Here's the code in Python Tutor. We can go all the way
to the beginning and if we execute this code, the first thing we do is
to find the first class, the bird class, put the
feathers and fly methods. Then we define the penguin
class which extends bird or is a child of bird
or a subclass of bird. Then we create a bird object, and objects know what they are. They'd keep a reference to
the class that created them. So P1 knows it's
a bird instance. P2 is going to be created
as a penguin instance, the object of that class. Then we're going to ask
P1 the burdens is to fly. What that's going
to do is go look in the bird class for a fly
method and execute that. That's going to
print birds can fly. Then we're going to come back and we're going
to execute on P2, remember P2 is a
penguin instance. We're going to execute
the fly methods. That's going to go
to the penguin class first and see if there's a
fly method and there is, it will execute that one. Now we'll see that
penguins can't fly. Penguins can swim. Then we're going to come
back and we're going to call P1 dot feathers. P1 again is a bird instance. We'll look for the feathers function or method in
that class and we see it, and we'll execute that and that'll say birds have feathers. Then we'll do the
same thing with P2. But P2 is a penguin instance. It will first look in
the penguin class. There is no feathers
method there, so it'll go up to
the parent class and execute the one in birds. Again, it'll say
birds have feathers. Remember that objects keep track of the class
that created them and that's where
they start looking whenever you execute a
function or a method, they say okay, is
that in my class? If it is, I go ahead
and execute that one. Even if there's one in my parent class with the same name, that's called overriding
up inherited method. But if there isn't one there, it'll go then to the parent
class. There isn't one there. It would go to the
grandparent class, and it would keep going until it found it
because it wouldn't have compiled if there
wasn't one to execute. That's a little a bit about how when a method is
called on an object, it decides which
method to execute.